<template>
  <div>
    <div>
      <h1>商品列表</h1>
      <el-form :inline="true" :model="pageFrom" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input
            v-model="pageFrom.keyWord"
            placeholder="请输入商品名称/SPU/Id"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadprodList">查询</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="onAddProd()">添加商品</el-button>
      <el-button type="danger" @click="onDeleteBatchProd()">批量删除</el-button>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="prodId" label="序号" />
        <el-table-column prop="prodSpu" label="SPU" />
        <el-table-column prop="prodKindName" label="商品类型" />
        <el-table-column prop="typeName" label="商品分类" />
        <el-table-column prop="prodName" label="商品名称" />
        <el-table-column prop="brandName" label="品牌" />
        <el-table-column prop="prodStatus" label="状态">
          <template #default="scope">
            <el-tag type="info" v-if="scope.row.prodStatus == 0">草稿</el-tag>
            <el-tag type="success" v-if="scope.row.prodStatus == 1"
              >上架</el-tag
            >
            <el-tag type="warning" v-if="scope.row.prodStatus == 2"
              >下架</el-tag
            >
            <el-tag type="danger" v-if="scope.row.prodStatus == 3">售罄</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="unitName" label="单位" />
        <el-table-column prop="tagName" label="标签" />
        <el-table-column prop="appr" label="供应商" />
        <el-table-column prop="prodImage" label="缩略图">
          <template #default="scope">
            <el-image
              v-if="scope.row.prodImage != null"
              style="width: 50px; height: 50px"
              :src="scope.row.prodImage"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="success"
              size="small"
              @click="onAddProdAtta(scope.row)"
              >商品附件</el-button
            >
            <el-button
              type="success"
              size="small"
              @click="onShowInfo(scope.row)"
              >商品明细</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 20px">
      <el-pagination
        v-model:current-page="pageFrom.pageNum"
        v-model:page-size="pageFrom.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加商品 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="商品添加" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="商品类型"
            :label-width="formLabelWidth"
            prop="prodKind"
          >
            <el-radio-group v-model="form.prodKind">
              <el-radio
                v-for="item in prodKindList"
                :key="item.dictId"
                :value="item.dictValue"
              >
                {{ item.dictName }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="商品分类"
            :label-width="formLabelWidth"
            prop="prodType"
          >
            <el-tree-select
              v-model="form.prodType"
              :data="typeList"
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item
            label="SPU"
            :label-width="formLabelWidth"
            prop="prodSpu"
          >
            <el-input v-model="form.prodSpu" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="prodName"
          >
            <el-input v-model="form.prodName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品品牌"
            :label-width="formLabelWidth"
            prop="brandId"
          >
            <el-select v-model="form.brandId" placeholder="请选择">
              <el-option
                v-for="item in brandListOption"
                :key="item.brandId"
                :label="item.brandName"
                :value="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品单位"
            :label-width="formLabelWidth"
            prop="unitId"
          >
            <el-select v-model="form.unitId" placeholder="请选择">
              <el-option
                v-for="item in unitList"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品标签"
            :label-width="formLabelWidth"
            prop="tagId"
          >
            <el-select v-model="form.tagId" placeholder="请选择">
              <el-option
                v-for="item in tagList"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="供应商"
            :label-width="formLabelWidth"
            prop="appr"
          >
            <el-input v-model="form.appr" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品缩略图"
            :label-width="formLabelWidth"
            prop="prodImage"
          >
            <el-upload
              class="avatar-uploader"
              :headers="headers"
              action="http://localhost:10010/brand/brand/uploadFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="form.prodImage" :src="form.prodImage" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 添加附件 -->
    <div>
      <el-dialog
        v-model="dialogAttaFormVisible"
        title="添加商品附件"
        width="500"
      >
        <el-form :model="attaForm" ref="ruleFormRef" :rules="ruleAtta">
          <el-form-item label="商品轮播图" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileList"
              :headers="headers"
              action="http://localhost:10010/brand/brand/uploadFile"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="商品视频" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileVideoList"
              class="upload-demo"
              :headers="headers"
              action="http://localhost:10010/brand/brand/uploadFile"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="handleVideoRemove"
              :limit="3"
            >
              <el-button type="primary">上传视频</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  作用于商品详情页顶部轮播的视频介绍,最大限制20MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="定时上架"
            :label-width="formLabelWidth"
            prop="upFlag"
          >
            <el-radio-group v-model="attaForm.upFlag">
              <el-radio :value="0">立即上架</el-radio>
              <el-radio :value="1">定时上架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <el-date-picker
              v-if="attaForm.upFlag == 1"
              v-model="attaForm.upTime"
              type="datetime"
              placeholder="请选择"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            label="定时下架"
            :label-width="formLabelWidth"
            prop="downFlag"
          >
            <el-switch
              v-model="attaForm.downFlag"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <el-date-picker
              v-if="attaForm.downFlag == 1"
              v-model="attaForm.downTime"
              type="datetime"
              placeholder="请选择"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAttaForm(ruleFormRef)">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {
  getProdList,
  deleteBatchProd,
  getDictByType,
  addProd,
  addProdAtta,
} from "../api/prod";
import { onMounted, ref } from "vue";
import { brandList, getSelectType } from "@/api/brand";
import { ElMessage, type TableInstance } from "element-plus";
import { ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { it } from "node:test";

import type { UploadUserFile } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const fileList = ref<UploadUserFile[]>([]);
const fileVideoList = ref<UploadUserFile[]>([]);
const multipleSelection = ref<any[]>([]);
const multipleTableRef = ref<TableInstance>();
const dialogFormVisible = ref(false);
const dialogAttaFormVisible = ref(false);
const formLabelWidth = "140px";
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const tableData = ref([]);
const brandListOption = ref([]);
const prodKindList = ref([]);
const unitList = ref([]);
const tagList = ref([]);
const typeList = ref([]);
const total = ref(0);
const headers = ref({
  token: sessionStorage.getItem("token"),
});

const onShowInfo = (row: any) => {
  router.push("/home/prodInfo/" + row.prodId);
};
const pageFrom = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
});
//品牌
const brandFrom = ref({
  pageNum: 1,
  pageSize: 99999,
});
const form = ref({
  appr: "",
  brandId: null,
  prodImage: "",
  prodKind: null,
  prodName: "",
  prodSpu: "",
  prodType: null,
  tagId: null,
  unitId: null,
});
const attaForm = ref({
  attaImages: "",
  attaVideo: "",
  createBy: "",
  downFlag: null,
  downTime: "",
  prodId: null,
  upFlag: null,
  upTime: "",
});

const rules = ref({
  appr: [{ required: true, message: "请输入供应商", trigger: "blur" }],
  brandId: [{ required: true, message: "请选择品牌", trigger: "blur" }],
  prodImage: [{ required: true, message: "请选择图片", trigger: "blur" }],
  prodKind: [{ required: true, message: "请选择类型", trigger: "blur" }],
  prodName: [{ required: true, message: "请输入名称", trigger: "blur" }],
  prodSpu: [{ required: true, message: "请输入SPU", trigger: "blur" }],
  prodType: [{ required: true, message: "请选择分类", trigger: "blur" }],

  tagId: [{ required: true, message: "请选择标签", trigger: "blur" }],
  unitId: [{ required: true, message: "请选择单位", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");

      addProd(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          loadprodList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//附件校验
const ruleAtta = ref({
  upFlag: [{ required: true, message: "请选择上架", trigger: "blur" }],
  downFlag: [{ required: true, message: "请输入下架", trigger: "blur" }],
});

const submitAttaForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      //多图片
      let image: any = [];
      fileList.value.forEach((item) => {
        image.push(item.response.data);
      });

      if (image.length <= 0) {
        ElMessage.error("还未选择商品轮播图");
        return;
      }
      attaForm.value.attaImages = JSON.stringify(image);
      if (fileVideoList.value.length <= 0) {
        ElMessage.error("还未上传视频");
        return;
      }
      attaForm.value.attaVideo = fileVideoList.value[0].response.data;

      addProdAtta(attaForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加附件成功");
          dialogAttaFormVisible.value = false;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
// const saveProdAtta = () => {
//   //多图片
//   let image: any = [];
//   fileList.value.forEach((item) => {
//     image.push(item.response.data);
//   });

//   attaForm.value.attaImages = JSON.stringify(image);
//   attaForm.value.attaVideo = fileVideoList.value[0].response.data;

//   addProdAtta(attaForm.value).then((res) => {
//     if (res.data.code == 200) {
//       ElMessage.success("添加附件成功");
//       dialogAttaFormVisible.value = false;
//     } else {
//       ElMessage.error(res.data.msg);
//     }
//   });
// };
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const handleVideoRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};
//保存商品
// const saveProd = () => {
//   addProd(form.value).then((res) => {
//     if (res.data.code == 200) {
//       ElMessage.success("添加成功");
//       dialogFormVisible.value = false;
//       loadprodList();
//     } else {
//       ElMessage.error(res.data.msg);
//     }
//   });
// };

//图片回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  form.value.prodImage = response.data;
};
const onAddProdAtta = (row: any) => {
  attaForm.value = {
    attaImages: "",
    attaVideo: "",
    createBy: "",
    downFlag: null,
    downTime: "",
    prodId: row.prodId,
    upFlag: null,
    upTime: "",
  };
  dialogAttaFormVisible.value = true;
};
//添加框
const onAddProd = () => {
  form.value = {
    appr: "",
    brandId: null,
    prodImage: "",
    prodKind: null,
    prodName: "",
    prodSpu: "",
    prodType: null,
    tagId: null,
    unitId: null,
  };
  dialogFormVisible.value = true;
};
//批量删除
const onDeleteBatchProd = () => {
  let ids: any = [];
  multipleSelection.value.forEach((item) => {
    ids.push(item.prodId);
  });

  if (ids.length == 0) {
    ElMessage.error("还未选择数据");
    return;
  }
  ElMessageBox.confirm("删除后不可恢复,确认删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteBatchProd(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadprodList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
//列表
const loadprodList = () => {
  getProdList(pageFrom.value).then((res) => {
    tableData.value = res.data.data.records;
    total.value = res.data.data.total;
  });
};
//每页条数
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pageFrom.value.pageSize = val;
  loadprodList();
};
//当前页数
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  pageFrom.value.pageNum = val;
  loadprodList();
};

//钩子函数
onMounted(() => {
  getSelectType().then((res) => {
    console.log("type", res);
    typeList.value = res.data.data;
  });
  brandList(brandFrom.value).then((res) => {
    console.log(res);
    brandListOption.value = res.data.data.records;
  });
  getDictByType(1).then((res) => {
    prodKindList.value = res.data.data;
  });
  getDictByType(2).then((res) => {
    unitList.value = res.data.data;
  });
  getDictByType(4).then((res) => {
    tagList.value = res.data.data;
  });

  loadprodList();
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
